<template>
  <div class="app-container">
    <el-dialog :visible="carouselVisible" class="dialog" width="800" @close="closeDialog()">
      <el-form
        ref="carouselList"
        :model="carouselList"
        :rules="rules">
        <el-form-item label="图片名称" prop="imageName" label-width="90px">
          <el-col :span="14" >
            <el-input v-model="carouselList.imageName" maxlength="50" placeholder="请填写图片名称" />
          </el-col>
        </el-form-item>
        <el-form-item label="图片顺序" prop="sort" label-width="90px">
          <el-col :span="14" >
            <el-input
              v-model="carouselList.sort"
              maxlength="1"
              type="text"
              placeholder="数值越小图片排序越靠前"
              @input="changeStr" />
          </el-col>
        </el-form-item>
        <el-form-item label="图片" prop="cost" class="add_tip" label-width="90px">
          <el-col :span="20" >
            <div style="width:302px" class="fl">
              <div class="thumbnail">
                <img v-show="carouselList.imageUrl" :src="carouselList.imageUrl" alt="">
              </div>
              <div class="uploadBox">
                <!-- <el-upload
                  ref="picUpload"
                  :before-remove="beforeRemove"
                  :before-upload="beforeAvatarUpload"
                  :on-success="(file, filelist) => change('coverImg', file, filelist)"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :file-list="fileList"
                  :data="uploadData"
                  :action="actionUrl"
                  :with-credentials= "false"
                  :model="carouselList.imageUrl"
                  multiple
                  class="upload-demo fl"
                  accept=".jpg,.jpeg,.png,.JPG,.JPEG,.gif,.Gif">
                  <el-button size="small" type="primary" plain>选择图片</el-button>
                </el-upload> -->
                <!-- :img-list.sync="carouselList.imageUrl" -->
                <vueCropper
                  :fixed-number="[18,9]"
                  :limit="1"
                  img-type="slt"
                  class="upload-demo fl"
                  @modalShowFn="getModalStatus" />
                <el-button class="btn_clear fr" size="small" type="info" plain @click="clearPic()">清除</el-button>
              </div>
            </div>
            <div class="fl tipBox">
              <p slot="tip" class="el-upload__tip">图片尺寸建议335*160</p>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item class="bottomButton">
          <el-button v-preventReClick type="primary" @click="updatereceiveList">确定</el-button>
          <el-button v-preventReClick type="info" @click="closeDialog()">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- <carouselList :choose-visible.sync="chooseVisible" :receive-data.sync="receiveData" @onReceiveData="receiveDataFn"/> -->
  </div>
</template>
<script>
import config from '@/utils/config';
// import carouselList from '@/components/carousel/list'
import { Message } from 'element-ui'
import vueCropper from '@/components/cropper'
import UploadImg from '@/components/cropper/uploadImage.vue'
export default {
  components: { vueCropper, UploadImg },
  props: {
    carouselVisible: {
      type: Boolean,
      required: true
    },
    editData: {
      type: Object,
      required: true
    },
    editIndex: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      name: 111,
      uploadData: {
        key: '',
        token: ''
      },
      tempData: {},
      goodsName: '', // 不需要传递给后台的字段， 提出来
      carouselList: {
        imageName: '',
        imageUrl: '',
        goodsId: '',
        sort: '',
        goodsName: ''
      },
      actionUrl: config.BaseUrl + '/storage/create',
      fileList: [],
      path: '',
      chooseVisible: false,
      receiveData: {}, // 接收子组件数据
      rules: {
        imageName: [
          { required: true, message: '请填写图片名称', trigger: 'blur' }
        ],
        sort: [
          { required: true, message: '请填写图片顺序,并且是数字', trigger: 'blur' }
        ],
        goodsId: [
          { required: false, message: '请选择链接', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    editData: {
      handler: function(nowVal, oldVal) {
        this.carouselList = nowVal
        console.log('editData数据变了', nowVal)
      },
      deep: true
    },
    'carouselVisible'(nowVal, oldVal) {
    //   console.log(nowVal)
    //   console.log(this.$refs.picUpload)
      if (nowVal && this.$refs.picUpload && this.editIndex === -1) {
        this.clearData()
      }
    }
  },
  created() {
    // this.clearData()
  },
  methods: {
    getModalStatus(url) {
      this.carouselList.imageUrl = url
    //   this.cropperImg = obj.cropperImg;
    //   this.isShowCropper = obj.cropperShow;
    //   console.log(this.cropperImg)
    //   console.log(this.isShowCropper)
    },
    receiveDataFn(val) {
      this.carouselList.goodsId = val.id
      this.goodsName = val.name
      this.carouselList.goodsName = val.name
    },
    replaceInput(value) {
      this.carouselList.imageName = this.validForbid(value)
    },
    changeStr(val) {
      this.carouselList.sort = val.replace(/[^\d]/g, '')
    },

    clearData() {
      this.carouselList.imageName = ''
      this.carouselList.imageUrl = ''
      this.carouselList.goodsId = ''
      this.carouselList.sort = ''
      this.carouselList.goodsName = ''
      this.$refs.picUpload.clearFiles()
    },
    updatereceiveList() {
      this.$refs.carouselList.validate((valid) => {
        if (valid) {
          if (this.carouselList.imageUrl === '') {
            Message.error('请选择一张图片')
            return false
          }
          this.tempData = this.carouselList
          console.log(this.tempData)
          this.$emit('updateFn', this.tempData, this.editIndex)
          this.closeDialog()
        }
      })
    },
    chooseLine() {
      this.chooseVisible = true
    },
    closeDialog() {
      this.$emit('update:carouselVisible', false)
      this.carouselList.imageUrl = ''
      this.carouselList.imageName = ''
      this.carouselList.sort = ''

      this.$refs['carouselList'].clearValidate();
    },
    beforeRemove(file, fileList) {
      console.log('file:::', file)
      console.log('fileList:::', fileList)
      if (file && file.status === 'success') {
        return this.$confirm(`确定移除 ${file.name}？`).then(() => {
          // let index = fileList
          console.log()
        })
      }
    },
    beforeAvatarUpload(file) {
      const isPNG = file.type === 'image/png'
      const isJPEG = file.type === 'image/jpeg'
      const isJPG = file.type === 'image/jpg'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isPNG && !isJPEG && !isJPG && !isGIF) {
        this.$message.error('上传头像图片只能是 jpg、png、jpeg、gif 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      this.uploadData.key = `upload_pic_${new Date().getTime()}_${file.name}`
      console.log('beforeAvatarUpload:', file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    clearPic() {
      this.$confirm('确定删除此图吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.carouselList.imageUrl = ''
        this.$refs.picUpload.clearFiles()
      }).catch(() => {})
    },
    change(type, file, fileList) {
      this.isUpload = true
      this.fileList = [];
      console.log('fileList:::', fileList)
      console.log('config.ImgUrl:::', config.ImgUrl)
      if (Number(fileList.response.code) === 200) {
        let obj;
        switch (type) {
          case 'coverImg': // 缩略图
            if (fileList.response.code === '200') {
              this.carouselList.imageUrl = fileList.response.data.url
            }
            break;
          case 'lbImg': // 轮播图
            obj = {
              posterImg: config.ImgUrl + fileList.response.data
            };
            // var urls = fileList.response.data.url.split('/')
            // var imgUrl = config.BaseUrl + '/' + urls[3] + '/' + urls[4] + '/' + urls[5]
            // console.log('图片地址：', imgUrl)
            this.isUpload = false
            this.imgsCurData.url = fileList.response.data.url
            // this.imgsCurData.curPath = fileList.url
            break;
        }
        Message.success('图片上传成功')

        // this.$store.dispatch('addListenerCoverImg', obj).then(() => {
        //   Message.success('图片上传成功')
        // }).catch((err) => {
        //   Message.error(err.err)
        // })
      }
    }
  }
}
</script>
<style scoped>
.fl{
    float:left
}

.fr{
    float:right
}
.thumbnail{
        width: 302px;
        height: 150px;
        border: 1px solid #eee;
        border-radius: 5px;
        display: flex;
    }

    .thumbnail img{
        width: 100% ;
    }
    .uploadBox{
        width: 100%;
        position: relative;
    }
    .btn_clear{
        /* position: absolute; */
        /* bottom: -38px; */
        /* right: 0; */
        margin-top: 4px;
        margin-left: 134px;
        padding: 10px 30px;
    }
    .line{
        border-bottom:1px solid #ddd;
    }
    .bottomButton{
        height: 80px;
        padding-top: 20px;
        text-align: center;
    }
    .goodsId{
        display: none;
    }
    .el-dialog__body{
        padding-bottom: 30px;
    }
    .el-dialog__wrapper .el-dialog{
        overflow-y: auto;
    }
    .tipBox{
        margin: 66px 0 0 20px;
    }
</style>
